
package com.wwy.monitor.controller;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.wwy.monitor.common.PageResult;
import com.wwy.monitor.common.ResponseEnum;
import com.wwy.monitor.common.ServiceResponse;
import com.wwy.monitor.model.enumeration.ComparatorTypeEnum;
import com.wwy.monitor.model.enumeration.DeleteEnum;
import com.wwy.monitor.model.tddl.dto.MonitorConfigDetailDTO;
import com.wwy.monitor.model.tddl.query.MonitorConfigDetailQuery;
import com.wwy.monitor.model.vo.MonitorDetailDelayTimeVo;
import com.wwy.monitor.service.MonitorConfigDetailService;
import com.wwy.monitor.util.DateUtil;
import com.wwy.monitor.util.OneLogUtil;
import com.wwy.monitor.util.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping(value = "/api/configDetail")
public class MonitorConfigDetailController {
    @Resource(name = "monitorConfigDetailService")
    private MonitorConfigDetailService monitorConfigDetailService;

    /**
     * 分页获取
     *
     * @return
     */
    @GetMapping("/page")
    @ResponseBody
    private ServiceResponse page(Integer pageNum, Integer pageSize, Long appId, Long startTime, Long endTime) {
        if (pageNum == null || pageSize == null) {
            return ServiceResponse.paramIllegal("分页参数不能为空");
        }
        MonitorConfigDetailQuery query = new MonitorConfigDetailQuery();
        if (appId != null) {
            query.setAppId(appId);
        }
        if (startTime != null && endTime != null) {
            Date startDate = new Date();
            Date endDate = new Date();
            startDate.setTime(startTime);
            endDate.setTime(endTime);
            query.setStartTime(startDate);
            query.setEndTime(endDate);
        }
        Integer offset = (pageNum - 1) * pageSize;
        query.setOffset(offset);
        query.setSize(pageSize);
        query.setIsDelete(DeleteEnum.NOT_DELETE.getValue());
        PageResult pageResult = new PageResult();
        pageResult.setCurrentPage(pageNum);
        pageResult.setPageSize(pageSize);
        pageResult.setTotalCount(monitorConfigDetailService.count(query));
        pageResult.setDatas(monitorConfigDetailService.selectByQuery(query));
        pageResult.getPages();
        return ServiceResponse.success(pageResult);
    }

    @GetMapping("/list")
    private ServiceResponse list(MonitorConfigDetailQuery query) {
        return ServiceResponse.success(monitorConfigDetailService.selectByCondition(query));
    }

    @PostMapping("/add")
    @ResponseBody
    private ServiceResponse add(HttpServletRequest request, @RequestBody MonitorConfigDetailDTO dto)
            throws IOException, ServletException {
        OneLogUtil.getOpLog("/api/configDetail/add", "配置添加", request);
        //参数校验
        if (!checkParameter(dto)) {
            return ServiceResponse.fail(ResponseEnum.PARAM_EMPTY.getCode(), ResponseEnum.PARAM_EMPTY.getDesc());
        }
        //期望值合法性校验
        if (!checkExcept(dto)) {
            return ServiceResponse.fail(ResponseEnum.PARAM_EMPTY.getCode(), "逻辑符号或期望值填写不合法");
        }
        //参数json格式校验
        String head = dto.getRequestHeader();
        if (StringUtils.isNotBlank(head)) {
            try {
                JSONObject.parseObject(head);
            } catch (JSONException e) {
                return ServiceResponse.fail(ResponseEnum.PARAM_ILLEGAL.getCode(), "请求头不是个合法json对象");
            }
        }
        //应用名称唯一校验
        int detailNameCount = monitorConfigDetailService.selectCountByDetailName(null, dto.getAppId(), dto.getDetailName());
        if (detailNameCount > 0) {
            return ServiceResponse.fail(ResponseEnum.PARAM_EMPTY.getCode(), "配置名称再该应用下已存在");
        }
        String empId = UserUtils.getBucEmpId(request);
        dto.setCreateUser(empId);
        dto.setIsDelete(DeleteEnum.NOT_DELETE.getValue());
        boolean flag = monitorConfigDetailService.insert(dto);
        if (!flag) {
            return ServiceResponse.fail(ResponseEnum.SAVE_EXCEPTION.getCode(), ResponseEnum.SAVE_EXCEPTION.getDesc());
        }
        return ServiceResponse.success(ResponseEnum.SUCCESS.getDesc());
    }

    @PostMapping("/update")
    @ResponseBody
    private ServiceResponse update(HttpServletRequest request, @RequestBody MonitorConfigDetailDTO dto)
            throws IOException, ServletException {
        OneLogUtil.getOpLog("/api/configDetail/update", "配置更新", request);
        //参数校验
        if (!checkParameter(dto) || null == dto.getId()) {
            return ServiceResponse.fail(ResponseEnum.PARAM_EMPTY.getCode(), ResponseEnum.PARAM_EMPTY.getDesc());
        }
        //期望值合法性校验
        if (!checkExcept(dto)) {
            return ServiceResponse.fail(ResponseEnum.PARAM_EMPTY.getCode(), "逻辑符号或期望值填写不合法");
        }
        //参数json格式校验
        String head = dto.getRequestHeader();
        if (StringUtils.isNotBlank(head)) {
            try {
                JSONObject.parseObject(head);
            } catch (JSONException e) {
                return ServiceResponse.fail(ResponseEnum.PARAM_ILLEGAL.getCode(), "请求头不是个合法的JSON对象");
            }
        }
        //应用名称唯一校验
        int detailNameCount = monitorConfigDetailService.selectCountByDetailName(dto.getId(), dto.getAppId(), dto.getDetailName());
        if (detailNameCount > 0) {
            return ServiceResponse.fail(ResponseEnum.PARAM_EMPTY.getCode(), "配置名称再该应用下已存在");
        }
        String empId = UserUtils.getBucEmpId(request);
        dto.setUpdateUser(empId);
        boolean flag = monitorConfigDetailService.updateById(dto);
        if (!flag) {
            return ServiceResponse.fail(ResponseEnum.UPDATE_EXCEPTION.getCode(), ResponseEnum.UPDATE_EXCEPTION.getDesc());
        }
        return ServiceResponse.success(ResponseEnum.SUCCESS.getDesc());
    }

    /**
     * 校验参数
     */
    private boolean checkParameter(MonitorConfigDetailDTO dto) {
        return (dto != null && dto.getAppId() != null && dto.getConfigId() != null && StringUtils.isNotBlank(dto.getUrl())
                && dto.getRate() != null && StringUtils.isNotBlank(dto.getRequestMethod())
                && StringUtils.isNotBlank(dto.getDetailName()));
    }

    /**
     * 期望值校验 规则：只有 = 时，允许期望值为数字或字符串，其他 统统为数字
     */
    private boolean checkExcept(MonitorConfigDetailDTO dto) {
        Integer comparator = dto.getComparator();
        String except = dto.getExcept();
        if ((null == comparator && StringUtils.isNotBlank(except)) ||
                (null != comparator && StringUtils.isBlank(except))) {
            return false;
        }
        if (null != comparator && StringUtils.isNotBlank(except) && ComparatorTypeEnum.EQUAL.getValue() != comparator) {
            try {
                Integer.parseInt(except);
                return true;
            } catch (Exception e) {
                return false;
            }
        } else {
            return true;
        }
    }

    @PostMapping("/delete")
    @ResponseBody
    private ServiceResponse delete(@RequestBody MonitorConfigDetailDTO dto) {
        if (dto.getId() == null) {
            return ServiceResponse.fail(ResponseEnum.PARAM_EMPTY.getCode(), ResponseEnum.PARAM_EMPTY.getDesc());
        }
        boolean flag = monitorConfigDetailService.deleteById(dto.getId());
        if (!flag) {
            return ServiceResponse.fail(ResponseEnum.DELETE_EXCEPTION.getCode(), ResponseEnum.DELETE_EXCEPTION.getDesc());
        }
        return ServiceResponse.success(ResponseEnum.SUCCESS.getDesc());
    }

    @PostMapping("/updateAlertDelayTime")
    @ResponseBody
    private ServiceResponse updateAlertDelayTimeById(HttpServletRequest request, @RequestBody MonitorDetailDelayTimeVo timeVo)
            throws IOException, ServletException {
        OneLogUtil.getOpLog("/api/configDetail/updateAlertDelayTime", "关闭提醒", request);
        if (timeVo.getId() == null || timeVo.getTimes() == null) {
            return ServiceResponse.fail(ResponseEnum.PARAM_EMPTY.getCode(), ResponseEnum.PARAM_EMPTY.getDesc());
        }
        MonitorConfigDetailDTO dto = new MonitorConfigDetailDTO();
        dto.setId(timeVo.getId());
        dto.setAlertDelayTime(DateUtil.getDateBeforeTimeByMin(timeVo.getTimes()));
        dto.setUpdateTime(new Date());
        dto.setUpdateUser(UserUtils.getBucEmpId(request));
        boolean flag = monitorConfigDetailService.updateAlertDelayTimeById(dto);
        if (!flag) {
            return ServiceResponse.fail(ResponseEnum.UPDATE_EXCEPTION.getCode(), ResponseEnum.UPDATE_EXCEPTION.getDesc());
        }
        return ServiceResponse.success(ResponseEnum.SUCCESS.getDesc());
    }
}